package com.hk.service.impl.kyc;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hk.commons.Constant;
import com.hk.commons.ConstantCard;
import com.hk.commons.HqlFilter;
import com.hk.commons.JsonUtils;
import com.hk.commons.LongId;
import com.hk.commons.RedisCilent;
import com.hk.commons.StringHelper;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.UserCard;
import com.hk.commons.entity.sys.SysUser;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.ICoupon;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IParameter;

@Service
public class UserCardImpl extends BaseServiceImpl<UserCard> implements
		IUserCard {

	private Logger logger = LoggerFactory.getLogger(UserCardImpl.class);
	@Autowired
	private IParameter parmService;

	@Autowired
	private ICard cardService;
	
	@Autowired
	private ICoupon couponService;

	@Override
	public UserCard findById(Long id) {
		UserCard result = null;
		if (id != null) {
			result = getById(id);
		}
		return result;
	}

	@Override
	public Long add(UserCard model) {
		long id = LongId.get();
		model.setId(id);
		model.setGetTime(System.currentTimeMillis());
		super.save(model);
		return 0L;
	}

	@Override
	public List<UserCard> getActiveUserCard() {
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addEQFilter("status", Constant.ACTIVITY_ACTIVE);
		List<UserCard> actList = findByFilter(hqlFilter);
		return actList;
	}

	@Override
	public void updateUserCardInfo(UserCard userCard, int cardStatus,
			Long orderId) {
		// 卡券的状态0:未使用， 1:已使用， 2， 已过期
		if (cardStatus == 1) {
			userCard.setStatus(1);
			userCard.setOrderId(orderId);
			userCard.setUseTime(System.currentTimeMillis());
		} else if (cardStatus == 2) {
			userCard.setStatus(2);
			userCard.setUseTime(System.currentTimeMillis());
		}
		super.update(userCard);
	}

	@Override
	public UserCard getFromRedis(Long orderId) {

		UserCard userCard = null;
		String key = ConstantCard.KEY + orderId;

		if (RedisCilent.existsKey(key)) {
			String userCardStr = RedisCilent.getString(key);

			userCard = JsonUtils.toBean(userCardStr, UserCard.class);
		}

		return userCard;
	}

	@Override
	public UserCard getByOrderId(Long orderId) {
		UserCard userCard = null;
		if (orderId != null) {
			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addEQFilter("orderId", orderId);
			List<UserCard> cardList = this.findByFilter(hqlFilter);
			if (cardList != null && cardList.size() > 0) {
				userCard = cardList.get(0);
			}
		}
		return userCard;
	}

	@Override
	public void addIntoRedis(UserCard userCard) {
		RedisCilent.setString(ConstantCard.KEY + userCard.getOrderId(),
				JsonUtils.toJson(userCard));
	}

	@Override
	public void deleteFromRedis(Long orderId) {
		String key = ConstantCard.KEY + orderId;
		if (RedisCilent.existsKey(key)) {
			RedisCilent.delKey(key);
		}

	}

	@Override
	public UserCard updateStatus(Long userCardId, Long orderId, Boolean status) {
		
		logger.info("更改加息券的状态userCardId={},orderId={}, status={}", userCardId,orderId, status);
		
		UserCard userCard = this.findById(userCardId);

		if (userCard != null) {
			if (status) {
				// 支付成功，则更改状态为已使用
				userCard.setStatus(ConstantCard.CARD_STATUS_ACTIVE);
				userCard.setOrderId(orderId);
				userCard.setUseTime(System.currentTimeMillis());
			} else {
				// 支付失败，则更改状态为未使用
				userCard.setOrderId(null);
				userCard.setUseTime(null);
				userCard.setStatus(ConstantCard.CARD_STATUS_NO_ACTIVE);
			}
			this.update(userCard);
		}
		return userCard;
	}

	@Override
	public Boolean checkUserCard(Integer cardId) {
		// 发送加息券
		Card card = cardService.findById(cardId);

		// 02 判断加息券是否存在，如果不存在则直接退出
		if (card == null) {
			logger.info("checkUserCard false , 卡券不存在 cardId = {}", cardId);
			return false;
		}

		return true;
	}

	/**
	 * 检查派送的加息券是否存在
	 * 
	 * @param cardId
	 * @return
	 */
	@Override
	public Card checkSendCard() {
		// 发送加息券
		// 01 判断参数配置是否存在，如果不能获取加息券id则直接退出
		Parameter parmCard = parmService.getByName(ConstantCard.SEND_CARD_ID);
		if (parmCard == null || StringHelper.isEmpty(parmCard.getValue01())) {
			logger.info("在参数表中找不到参数 SEND_CARD_ID， 或参数值为空");
			return null;
		}

		// 发送加息券
		Integer cardId = Integer.valueOf(parmCard.getValue01());

		Card card = cardService.findById(cardId);

		// 02 判断加息券是否存在，如果不存在则直接退出
		if (card == null) {
			logger.info("checkUserCard false , 卡券不存在 cardId = {}", cardId);
			return null;
		}

		return card;
	}

	@Override
	public Integer sendCardToUsers(List<SysUser> userList) {
		Integer result = 0;

		for (SysUser user : userList) {
			if (sendCardToUser(user)) {
				result++;
			}
		}

		return result;
	}

	@Override
	public Boolean sendCardToUser(SysUser user) {
		Card card = checkSendCard();

		if (card == null) {
			return false;
		}

		Integer cardId = card.getId();

		// 发放加息券
		UserCard userCard = new UserCard(user.getId(), cardId);
		// 01 给用添加卡券
		this.add(userCard);

		// 02 更新卡券的已用数目，加1
		card.setUsedNum(card.getUsedNum() + 1);
		cardService.update(card);

		return true;
	}

}
